package org.example;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class AA_RGB {


    public static void main(String[] args) throws IOException {
        String pngPath = "D:\\Documents\\workspaces\\Gitee\\java-projects\\untitled\\src\\main\\resources\\ame\\Snipaste.png";
        String rawPath = "output.raw";
        String outputPngPath = "output.png";

        // 读取PNG图片
        BufferedImage image = readImage(pngPath);

        // 转换PNG到RAW
        convertToRaw(image, rawPath);

        // 从RAW转换回PNG
        BufferedImage rawImage = convertFromRaw(rawPath, image.getWidth(), image.getHeight());

        // 保存转换后的PNG图片
        saveImage(rawImage, outputPngPath);
    }

    private static BufferedImage readImage(String path) throws IOException {
        return ImageIO.read(new File(path));
    }

    private static void convertToRaw(BufferedImage image, String outputPath) throws IOException {
        int width = image.getWidth();
        int height = image.getHeight();
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(outputPath))) {
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int rgb = image.getRGB(x, y);
                    dos.writeInt(rgb);
                }
            }
        }
    }

    private static BufferedImage convertFromRaw(String inputPath, int width, int height) throws IOException {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        try (DataInputStream dis = new DataInputStream(new FileInputStream(inputPath))) {
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int rgb = dis.readInt();
                    image.setRGB(x, y, rgb);
                }
            }
        }
        return image;
    }

    private static void saveImage(BufferedImage image, String path) throws IOException {
        ImageIO.write(image, "png", new File(path));
    }

}